<script setup lang="tsx">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useRouter, useRoute } from 'vue-router'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import {
  exportVerifyRecordApi,
  adminExportVerifyRecordApi,
  groupBuyPageGroupApi
} from '@/api/Activity'
import { useUserStore } from '@/store/modules/user'
import { formatTime } from '@/utils'

const userStore = useUserStore()

const { t } = useI18n()
const { go } = useRouter()
const { query } = useRoute()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const api = groupBuyPageGroupApi
    const res = await api({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      activeId: unref(query.id as any),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'expand',
    type: 'expand',
    search: {
      hidden: true
    },
    slots: {
      default: (data) => {
        const { row } = data
        return (
          <div class="ml-60px">
            <el-table data={row.items} border style="width: 70%">
              <el-table-column prop="itemNo" label="团员编号" />
              <el-table-column
                label="参团人员"
                formatter={(ros) => (
                  <div>
                    <div>
                      <el-tag class="mr-2" v-show={ros.groupLead}>
                        团长
                      </el-tag>
                      {ros.nickName}
                    </div>
                    <div>{ros.mobile}</div>
                  </div>
                )}
              />
              <el-table-column
                prop="free"
                label="免单"
                formatter={(ros) => <div>{ros.free ? '是' : '否'}</div>}
              />
              <el-table-column
                prop="orderNo"
                label="订单编号"
                formatter={(ros) => (
                  <>
                    <span v-show={ros.orderNo === '0元开团'}>{ros.orderNo}</span>
                    <router-link
                      v-show={ros.orderNo !== '0元开团'}
                      to={{
                        path: '/order/groupBuy',
                        query: { id: query.id, orderNo: ros.orderNo }
                      }}
                    >
                      {ros.orderNo}
                    </router-link>
                  </>
                )}
              />
              <el-table-column prop="createTime" label="参团时间" />
            </el-table>
          </div>
        )
      }
    }
  },
  {
    field: 'id',
    label: '团组编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 120
    }
  },
  {
    field: 'leadNickName',
    label: '团长',
    search: {
      hidden: true,
      componentProps: {
        placeholder: '请输入团长名称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 180,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.leadNickName}</div>
              <div>{row.leadMobile}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'groupLeadKeyword',
    label: '团长/手机号码',
    search: {
      hidden: false,
      componentProps: {
        placeholder: '请输入团长/手机号码'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'currentNum',
    label: '参团人数',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 120
    }
  },
  {
    field: 'status',
    label: '团组状态',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 180,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{statusMapping[row.status]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'createTime',
    label: '开团时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'groupTime',
    label: '成团时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    }
  }
])

const statusMapping = {
  1: '待成团',
  2: '已成团',
  3: '拼团失败'
}

const { allSchemas } = useCrudSchemas(crudSchemas)
const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { createTime, groupTime, ...rest } = params
  let startCreateTime, endCreateTime
  if (createTime && createTime.length > 0) {
    startCreateTime = createTime[0]
    endCreateTime = createTime[1]
  }
  let startGroupTime, endGroupTime
  if (groupTime && groupTime.length > 0) {
    startGroupTime = groupTime[0]
    endGroupTime = groupTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startCreateTime,
    endCreateTime,
    startGroupTime,
    endGroupTime,
    ...rest
  }
  getList()
}
const handleDownload = async (params: any) => {
  const { createTime, groupTime, ...rest } = params
  let startCreateTime, endCreateTime
  if (createTime && createTime.length > 0) {
    startCreateTime = createTime[0]
    endCreateTime = createTime[1]
  }
  let startGroupTime, endGroupTime
  if (groupTime && groupTime.length > 0) {
    startGroupTime = groupTime[0]
    endGroupTime = groupTime[1]
  }
  const currentDate = new Date()
  const time = formatTime(currentDate, 'yyyyMMddHHmmss')
  const num = Math.floor(Math.random() * 900000) + 100000
  const downloadApi = userStore.userInfo?.roles.includes('商家')
    ? adminExportVerifyRecordApi
    : exportVerifyRecordApi
  const res = await downloadApi({
    startCreateTime,
    endCreateTime,
    startGroupTime,
    endGroupTime,
    activeId: unref(query.id as any),
    ...rest
  })
  const correctMimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  const url = window.URL.createObjectURL(new Blob([res.data], { type: correctMimeType }))
  let link = document.createElement('a')
  link.href = url
  link.download = `团组记录${time}${num}`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentDetailWrap class="flex-[3] ml-20px" title="核销记录">
      <template #header>
        <ElButton @click="go(-1)">
          {{ t('common.back') }}
        </ElButton>
      </template>
      <Search
        :schema="allSchemas.searchSchema"
        @download="handleDownload"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentDetailWrap>
  </div>
</template>
